#include <QCoreApplication>
#include <QSettings>
#include <QFile>
#include <QDir>
#include <QString>
#include "httplistener.h"
#include "httprequesthandler.h"
#include "helloworldcontroller.h"
#include "listdatacontroller.h"
#include "requestmapper.h"
#include "global.h"

using namespace stefanfrings;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

//    QFile file("‪D:/qt/workspace/MyFirstWebApp/etc/webapp1.ini");
    QFile file("D:\\qt\\workspace\\MyFirstWebApp\\etc\\webapp1.ini");
    QString configFileName;
    if (!file.exists()) {
        return a.exec();
    }
    configFileName = QDir(file.fileName()).canonicalPath();
    qDebug("Using config file %s", qPrintable(configFileName));

    //Configure logging
    QSettings *logSettings = new QSettings(configFileName, QSettings::IniFormat, &a);
    logSettings->beginGroup("logging");
    logger = new FileLogger(logSettings, 10000, &a);
    logger->installMsgHandler();
    //Log the library version
    qDebug("QtWebApp has version %s", getQtWebAppLibVersion());

    //Session store
    QSettings *sessionSettings =
        new QSettings(configFileName, QSettings::IniFormat, &a);
    sessionSettings->beginGroup("sessions");
    sessionStore = new HttpSessionStore(sessionSettings, &a);

    //Static file controller
    QSettings *fileSettings = new QSettings(configFileName, QSettings::IniFormat, &a);
    fileSettings->beginGroup("files");
    staticFileController = new StaticFileController(fileSettings, &a);

    //Configure template cache
    QSettings *templateSettings = new QSettings(configFileName, QSettings::IniFormat, &a);
    templateSettings->beginGroup("templates");
    templateCache = new TemplateCache(templateSettings, &a);

    //Load the configuration file
    QSettings *listenerSettings =
        new QSettings(configFileName, QSettings::IniFormat, &a);
    qDebug("config file loaded");
    listenerSettings->beginGroup("listener");

    //Start the HTTP server
    new HttpListener(listenerSettings, new RequestMapper(&a), &a);
    return a.exec();
}
